package es

import (
	"context"
	"errors"
	"fmt"
	"github.com/go-playground/validator/v10"
	"github.com/olivere/elastic/v7"
)

type EsConfig struct {
	Host     string `json:"host" validate:"required"`
	Port     string `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"`
}

func (c *EsConfig) BuildClient() (client *elastic.Client, err error) {
	// 1. 配置验证
	if err = validator.New().Struct(c); err != nil {
		return nil, err
	}
	// 2. 创建客户端
	url := fmt.Sprintf("%s:%s", c.Host, c.Port)
	client, err = elastic.NewClient(
		elastic.SetURL(url),
		elastic.SetBasicAuth(c.User, c.Password),
	)
	if err != nil {
		return nil, err
	}
	// 3. 测试链接
	_, code, err := client.Ping(url).Do(context.Background())
	if err != nil {
		return client, errors.New(fmt.Sprintf("%d：%s", code, err.Error()))
	}
	return client, err
}
